#define _CRT_SECURE_NO_WARNINGS
#include "Game.h"
#include <string.h>

Game::Game(HINSTANCE hIns, char* windowName, int width, int height)
{
	this->hInstance = hIns;
	this->_height = height;
	this->_width = width;
	_name = new char[strlen(windowName)];
	strcpy(_name, windowName);
	d3ddev = NULL;
	d3d = NULL;
}


Game::~Game(void)
{
}

bool Game::InitWindow()
{
	WNDCLASSEX wndclass;
	wndclass.cbSize = sizeof(WNDCLASSEX);
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hIconSm = 0;
	wndclass.hIcon = 0;
	wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
	wndclass.hInstance = this->hInstance;
	wndclass.lpfnWndProc = (WNDPROC)WinProc;
	wndclass.lpszClassName = "Game";
	wndclass.lpszMenuName = NULL;
	wndclass.style = CS_HREDRAW | CS_VREDRAW;

	if (!RegisterClassEx(&wndclass))
	{
		return false;
	}
	this->hwnd = CreateWindow(
		"Game",//ten class dang ki cua so
		this->_name,// ten cua so
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		this->_width,
		this->_height,
		NULL,
		NULL,
		this->hInstance,
		NULL);
	if (!this->hwnd)
		return false;
	ShowWindow(this->hwnd, SW_NORMAL);
	UpdateWindow(this->hwnd);
	return true;
}
bool Game::InitDX()
{
	//tao doi tuong dx
	this->d3d = Direct3DCreate9(D3D_SDK_VERSION);
	if (d3d == NULL)
		return false;
	D3DPRESENT_PARAMETERS d3dpp;
	ZeroMemory(&d3dpp, sizeof(d3dpp));
	//dinh nghia man hinh
	d3dpp.BackBufferCount = 1;
	d3dpp.BackBufferFormat = D3DFORMAT::D3DFMT_UNKNOWN;
	d3dpp.Windowed = true;
	d3dpp.BackBufferHeight = this->_height;
	d3dpp.BackBufferWidth = this->_width;
	d3dpp.SwapEffect = D3DSWAPEFFECT::D3DSWAPEFFECT_DISCARD;
	d3dpp.hDeviceWindow = this->hwnd;
	//Tao thiet bi

	HRESULT hr = d3d->CreateDevice(D3DADAPTER_DEFAULT,//chon card man hinh
		D3DDEVTYPE::D3DDEVTYPE_HAL,//loai thiet bi
		this->hwnd,//cua so game
		D3DCREATE_SOFTWARE_VERTEXPROCESSING,
		&d3dpp,//thong so card
		&this->d3ddev//out bien kiem soat card man hinh
		);
	if (FAILED(hr))
	{
		return false;
	}
	return true;
}
void Game::Load()
{

}

HRESULT CALLBACK Game::WinProc(HWND hwnd, UINT	message, WPARAM wParam, LPARAM lParam)
{
	if (message == WM_DESTROY)
	{
		PostQuitMessage(0);
	}
	return DefWindowProc(hwnd, message, wParam, lParam);
}

void Game::Run()
{
	MSG msg;
	ZeroMemory(&msg, sizeof(MSG));
	while (msg.message != WM_QUIT)
	{
		if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			this->Render();
		}
	}
}

void Game::Render()
{
	this->d3ddev->Clear(1, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 255, 255), 1, NULL);
	this->d3ddev->Present(NULL, NULL, NULL, NULL);
}